All files / src/app/api/support/tickets/[id]/messages route.ts

0% Statements 0/157
100% Branches 0/0
0% Functions 0/1
0% Lines 0/157

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158                                                                                                                                                                                                                                                                                                                           
export const dynamic = "force-dynamic";

/**
 * Support Ticket Messages API
 * GET /api/support/tickets/[id]/messages - Get ticket messages
 * POST /api/support/tickets/[id]/messages - Add message to ticket
 */

import { NextRequest, NextResponse } from "next/server";
import { Session } from "next-auth";
import { prisma } from "@/lib/prisma";
import { CreateMessageSchema } from "@/lib/validation/support-schemas";
import { notifyAgentOfCustomerReply } from "@/lib/support/notification-utils";
import { TicketStatus, MessageSenderType, SupportTicketWithRelations } from "@/types/support";
import { logger } from "@/lib/logging";
import {
  withErrorHandling,
  withAuth,
  successResponse,
  createdResponse,
  ApiError } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";

/**
 * GET /api/support/tickets/[id]/messages
 * Get ticket messages (customer view - excludes internal messages)
 */
async function handleGet(
  _request: NextRequest,
  context: RouteContext | undefined,
  session: Session
): Promise<NextResponse> {
  if (!context?.params) {
    throw ApiError.invalidId("ticket");
  }

  const { id } = await context.params;
  const userId = Number(session.user.id);

  // Verify ticket exists and belongs to user
  const ticket = await prisma.supportTicket.findUnique({
    where: { id },
    select: { id: true, userId: true }});

  if (!ticket) {
    throw ApiError.notFound("Ticket", id);
  }

  if (ticket.userId !== userId) {
    throw ApiError.forbidden("Access denied");
  }

  // Get messages (exclude internal messages for customers)
  const messages = await prisma.supportMessage.findMany({
    where: {
      ticketId: id,
      isInternal: false},
    include: {
      sender: {
        select: { id: true, name: true }},
      attachments: true},
    orderBy: { createdAt: "asc" }});

  return successResponse(messages);
}

export const GET = withErrorHandling(withAuth(handleGet));

/**
 * POST /api/support/tickets/[id]/messages
 * Add message to ticket (customer reply)
 */
async function handlePost(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session
): Promise<NextResponse> {
  if (!context?.params) {
    throw ApiError.invalidId("ticket");
  }

  const { id } = await context.params;
  const userId = Number(session.user.id);
  const userName = session.user.name || "Customer";

  // Verify ticket exists and belongs to user
  const ticket = await prisma.supportTicket.findUnique({
    where: { id },
    include: {
      assignedTo: {
        select: { id: true, name: true, email: true }}}});

  if (!ticket) {
    throw ApiError.notFound("Ticket", id);
  }

  if (ticket.userId !== userId) {
    throw ApiError.forbidden("Access denied");
  }

  // Check if ticket is closed/cancelled
  if (ticket.status === TicketStatus.CLOSED || ticket.status === TicketStatus.CANCELLED) {
    throw ApiError.validation("Cannot add messages to a closed ticket");
  }

  // Validate input
  const body = await request.json();
  const validationResult = CreateMessageSchema.safeParse(body);
  if (!validationResult.success) {
    throw ApiError.validation(
      "Validation failed",
      validationResult.error.flatten().fieldErrors
    );
  }

  const data = validationResult.data;

  // Create the message
  const message = await prisma.supportMessage.create({
    data: {
      ticketId: id,
      senderType: MessageSenderType.CUSTOMER,
      senderId: userId,
      senderName: userName,
      content: data.content,
      isInternal: false, // Customer messages are never internal
    },
    include: {
      sender: {
        select: { id: true, name: true }},
      attachments: true}});

  // Update ticket status to AWAITING_AGENT if it was AWAITING_CUSTOMER
  if (ticket.status === TicketStatus.AWAITING_CUSTOMER) {
    await prisma.supportTicket.update({
      where: { id },
      data: { status: TicketStatus.AWAITING_AGENT }});
  }

  // Notify assigned agent
  if (ticket.assignedToId) {
    await notifyAgentOfCustomerReply(
      ticket as unknown as SupportTicketWithRelations,
      userName
    );
  }

  logger.info("Customer message added to ticket", {
    category: "API",
    ticketId: id,
    messageId: message.id,
    userId});

  return createdResponse(message);
}

export const POST = withErrorHandling(withAuth(handlePost));